package cc.orange.mainView;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import cc.orange.BuildConfig;
import cc.orange.adapter.MsgConAdapter;
import cc.orange.base.BaseActivity;
import cc.orange.entity.BaseEntity;
import cc.orange.entity.ChatAnswerEntity;
import cc.orange.entity.ChatHistoryEntity;
import cc.orange.http.ApiService;
import cc.orange.utils.SoftKeyBoardListener;
import cc.orange.utils.emojis.EmoticonBoard;
import cc.orange.utils.emojis.RongUtils;

import cc.orange.databinding.ActivityConversationListBinding;

import cc.orange.R;

import cc.orange.entity.IsLoginsEntity;
import cc.orange.utils.ZXToastUtil;
import demo.smart.access.xutlis.util.ZXAppUtil;
import demo.smart.access.xutlis.util.ZXSystemUtil;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;

//import com.tendcloud.tenddata.TalkingDataSDK;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.os.Handler;

import org.greenrobot.eventbus.EventBus;

public class ConversationListActivity extends BaseActivity implements View.OnClickListener{

    private ActivityConversationListBinding binding;
    private String uid;
    private int type_jin;
    private MsgConAdapter adapter;
    private List<ChatHistoryEntity.Data.ListEntity> list = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_conversation_list);
        uid = getIntent().getStringExtra("uid");
        type_jin = getIntent().getIntExtra("type_jin",0);
        binding.talkTab1.setText(getIntent().getStringExtra("name"));
        binding.inputPanelEmojiBtn.setOnClickListener(this);
        binding.talkTab3.setOnClickListener(this);
        binding.talkTab2.setOnClickListener(this);
        getKeyBoard();
        initViews();
        findChat();

        if(type_jin == 1){
            saveChat(uid,"嗨~ 聊聊天吧？");
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
//            chatAnswer(uid);
            list.clear();
            findChat();
        }
    };

    private void initViews() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//        linearLayoutManager.setStackFromEnd(true);
        binding.talkMsgList.setLayoutManager(linearLayoutManager);
        adapter = new MsgConAdapter(list);
        binding.talkMsgList.setAdapter(adapter);

        TextWatcher mTextWatcher = new TextWatcher() {
            private int start;
            private int count;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
//                if (AndroidEmoji.isEmoji(s.subSequence(start, start + count).toString())) {
//                    binding.editBtn.removeTextChangedListener(this);
//                    String resultStr = AndroidEmoji.replaceEmojiWithText(s.toString());
//                    binding.editBtn.setText(AndroidEmoji.ensure(resultStr), TextView.BufferType.SPANNABLE);
//                    binding.editBtn.setSelection(binding.editBtn.getText().length());
//                    binding.editBtn.addTextChangedListener(this);
//                }
//                String s1 = binding.editBtn.getText().toString();
//                if(TextUtils.isEmpty(s1)){
//                    binding.talkSend.setBackgroundResource(R.drawable.shape_8e_13);
//                }else{
//                    binding.talkSend.setBackgroundResource(R.drawable.shape_home_title);
//                }
            }
        };

        binding.talkSend.addTextChangedListener(mTextWatcher);


        binding.talkSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s1 = binding.editBtn.getText().toString();
                if(!TextUtils.isEmpty(s1)){
                    saveChat(uid,s1);
                    forceSetSoftInputKeyBoard(false);
                    binding.editBtn.setText("");
                }
            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().post(new IsLoginsEntity(true));
//        TalkingDataSDK.onPageEnd(this, getLocalClassName());
    }

    public void forceSetSoftInputKeyBoard(boolean isShow) {
        InputMethodManager imm = (InputMethodManager) getApplication().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            if (isShow) {
                binding.editBtn.requestFocus();
                imm.showSoftInput(binding.editBtn, 0);
            } else {
                imm.hideSoftInputFromWindow(binding.editBtn.getWindowToken(), 0);
                binding.editBtn.clearFocus();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.input_panel_emoji_btn:
                forceSetSoftInputKeyBoard(false);
                EmoticonBoard mEmoticonBoard = new EmoticonBoard(ConversationListActivity.this, binding.talkeRel1, "123",binding.editBtn);
                binding.converRel1.removeAllViews();
                binding.converRel1.addView(mEmoticonBoard.getView());

                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.converRel1.getLayoutParams();
                layoutParams.height = RongUtils.dip2px(230);
                binding.converRel1.setLayoutParams(layoutParams);
                break;
            case R.id.talk_tab3:
                Intent intent = new Intent(ConversationListActivity.this, InfoSetActivity.class);
                intent.putExtra("uid",uid);
                startActivity(intent);
                break;
            case R.id.talk_tab_2:
                finish();
                break;
        }
    }


    public void getKeyBoard(){

        //监听软键盘弹出，并获取软键盘高度
        SoftKeyBoardListener.setListener(ConversationListActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                //软键盘弹起事件  并给View设置高度
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.converRel1.getLayoutParams();
                layoutParams.height = RongUtils.dip2px(0);
                binding.converRel1.setLayoutParams(layoutParams);
            }

            @Override
            public void keyBoardHide(int height) {
                //软键盘隐藏事件  并给View设置高度为0
            }
        });
    }


    // 查找聊天记录
    private void findChat(){
        RetrofitFactory.create(ApiService.class)
                .findChat(getTokens(),uid)
                .enqueue(new DefaultCallback<ChatHistoryEntity>() {
                    @Override
                    public void onStart(Call<ChatHistoryEntity> call) {
                        showLoading_base(ConversationListActivity.this);
                    }

                    @Override
                    public void onError(Call<ChatHistoryEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<ChatHistoryEntity> call, ChatHistoryEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            list.addAll(baseEntity.getData().getList());
                            Collections.reverse(list);
                            adapter.setNamePhoto(baseEntity.getData().getName(),baseEntity.getData().getPhoto(),uid);
                            adapter.notifyDataSetChanged();
                            if(list.size() > 1) {
                                binding.talkMsgList.smoothScrollToPosition(adapter.getItemCount() - 1);
                            }
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                        if(list.size() > 0) {
                            handler.sendEmptyMessageDelayed(0, 10000);
                        }
                    }
                });
    }

    // 保存聊天信息
    private void saveChat(String uid,String content){

//        SaveChatEntity entitys = new SaveChatEntity(uid,content);
//        Gson gss = new Gson();
//        String s = gss.toJson(entitys);
//        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());


        RetrofitFactory.create(ApiService.class)
                .saveChat(getTokens(),uid,content
                        ,ZXAppUtil.getPackageName(),""+BuildConfig.APP_CHANNEL,""+ZXSystemUtil.getVersionCode())
                .enqueue(new DefaultCallback<BaseEntity>() {
                    @Override
                    public void onStart(Call<BaseEntity> call) {
                    }

                    @Override
                    public void onError(Call<BaseEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ChatHistoryEntity.Data.ListEntity ll = new ChatHistoryEntity.Data.ListEntity();
                            ll.setChattingRecords(content);
                            ll.setAcceptUserId(Integer.valueOf(uid));
                            ll.setClassify(1);
                            list.add(ll);
                            adapter.notifyDataSetChanged();
                            if(list.size() > 1) {
                                binding.talkMsgList.smoothScrollToPosition(adapter.getItemCount() - 1);
                            }
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }

                        handler.removeMessages(0);
                        handler.sendEmptyMessageDelayed(0, 10000);
                    }
                });
    }

    //
//    private void chatAnswer(String uid){
//
////        SaveChatEntity entitys = new SaveChatEntity(uid,content);
////        Gson gss = new Gson();
////        String s = gss.toJson(entitys);
////        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());
//
//        RetrofitFactory.create(ApiService.class)
//                .chatAnswer(getTokens(),uid)
//                .enqueue(new DefaultCallback<ChatAnswerEntity>() {
//                    @Override
//                    public void onStart(Call<ChatAnswerEntity> call) {
//                    }
//
//                    @Override
//                    public void onError(Call<ChatAnswerEntity> call, HttpError error) {
//                    }
//
//                    @Override
//                    public void onSuccess(Call<ChatAnswerEntity> call, ChatAnswerEntity baseEntity) {
//                        if(baseEntity.getCode() == 0){
//                            ChatHistoryEntity.Data.ListEntity ll = new ChatHistoryEntity.Data.ListEntity();
//                            ll.setChattingRecords(baseEntity.getData().getDetails());
//                            ll.setAcceptUserId(Integer.valueOf(uid));
//                            ll.setClassify(0);
//                            list.add(ll);
//                            adapter.notifyDataSetChanged();
//                            if(list.size() > 1) {
//                                binding.talkMsgList.smoothScrollToPosition(adapter.getItemCount() - 1);
//                            }
//                        }else{
//                            ZXToastUtil.showToast(baseEntity.getMsg());
//                        }
//                    }
//                });
//    }



    // 发消息给客服
    private void returnKefu(String content){
        RetrofitFactory.create(ApiService.class)
                .returnKefu(getTokens(),content)
                .enqueue(new DefaultCallback<BaseEntity>() {
                    @Override
                    public void onStart(Call<BaseEntity> call) {
                        showLoading_base(ConversationListActivity.this);
                    }

                    @Override
                    public void onError(Call<BaseEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ChatHistoryEntity.Data.ListEntity ll = new ChatHistoryEntity.Data.ListEntity();
                            ll.setChattingRecords(content);
                            ll.setAcceptUserId(Integer.valueOf(uid));
                            ll.setClassify(1);
                            list.add(ll);
                            adapter.notifyDataSetChanged();
                            if(list.size() > 1) {
                                binding.talkMsgList.smoothScrollToPosition(adapter.getItemCount() - 1);
                            }
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
//        TalkingDataSDK.onPageBegin(this, getLocalClassName());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(0);
    }
}